package housekeeping.service.Impl;

import housekeeping.mapper.UserLoginMapper;
import housekeeping.pojo.UserAccounts;
import housekeeping.service.UserLoginService;
import housekeeping.util.JwtUtil;
import housekeeping.util.RedisUtil;
import housekeeping.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @Author Du
 * @Date 2025/7/7
 * @注释 用户登录业务实现类
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public ServerResult<?> login(UserAccounts user) {
        String account = user.getAccount();
        String password = user.getPassword(); // 前端已加密为MD5

        // 查询账号信息
        UserAccounts storedUser = userLoginMapper.selectByAccount(account);
        if (storedUser == null) {
            return ServerResult.error(401, "用户名或密码错误");
        }

        if (!storedUser.getPassword().equals(password)) {
            return ServerResult.error(401, "用户名或密码错误");
        }


        String role = storedUser.getRole();
        // 生成 token
        String token = JwtUtil.generateToken(account, role);

        // 将用户信息存入Redis，设置过期时间
        redisUtil.saveUserSession(token, account, role);

        // 构建响应数据
        Map<String, Object> response = new HashMap<>();
        response.put("account", account);
        response.put("role", role);
        response.put("token", token);

        return ServerResult.ok(response);
    }
}
